layui.define(['layer', 'table', 'form', 'admin', 'util'], function (exports) { // 也可以依赖其他模块

    let form = layui.form, n = layui.admin, t = n.tabsPage, r = layui.$, util = layui.util, laydate = layui.laydate;
    let tabId = 'layui-table-main', o = "layadmin-layout-tabs"
    let pUrl, title;
    let activeTabTitle = r(parent.document).find('.layui-tab .layui-this>span').text(); // 获取标题
    let mArea, mMaxmin, table, isOpenTab, myToolbar;
    // 自定义其他区域的高度
    let pageParams = {
        layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], // 功能布局
        limits: [15, 20, 25, 30, 35, 40, 45, 50],
        curr: 1 // 重新从第 1 页开始
    };
    let whereData = {}
    let defaultToolbar = [
        'filter',
        {
            name: 'exports',
            onClick: function (obj) {
                // 当前示例配置项
                // 弹出面板
                obj.openPanel({
                    list: [ // 列表
                        '<li data-type="all">导出全部数据</li>',
                        '<li data-type="xlsx">导出当前数据</li>'
                    ].join(''),
                    done: function (panel, list) { // 操作列表
                        list.on('click', function () {
                            var type = $(this).data('type');
                            console.log(title + "----------");
                            if (type === 'all') {
                                var data = form.val('searchForm');
                                console.log(JSON.stringify(data))
                                post(__basePath + tabUrl() + "/export", data, function (result) {
                                    table.exportFile(tabId, result.data, {
                                        type: "xls",
                                        title: title + new Date().Format("yyyyMMddhhmmss")
                                    });
                                    layer.msg('导出成功！', {icon: 1})
                                }, function () {
                                    layer.msg('导出失败！', {icon: 5})
                                })

                            } else if (type === 'xlsx') {
                                table.exportFile(tabId, null, {
                                    type: "xls",
                                    title: title + new Date().Format("yyyyMMddhhmmss")
                                });
                                layer.msg('导出成功！', {icon: 1})
                            }
                        });
                    }
                });
            }
        }
    ]
    form.set({
        autocomplete: 'off' // 阻止 input 框默认的自动输入完成功能
    });
    const tableLoad = {
        //cols,数据列  onEvent(obj.event, obj.data._id, obj) 按钮点击回调, area[] 弹出框的大小, maxmin 是否显示最大化和最小化, tree treeTable 默认配置 tab 代表tab方式打开
        render: function (options) {
            form.set({
                autocomplete: 'off' // 阻止 input 框默认的自动输入完成功能
            })
            if (options.tree) {
                table = layui.treeTable;
            } else table = layui.table;
            if (options.noPage === true) {
                pageParams = false;
            }
            whereData = options.whereData;
            pUrl = tabUrl();
            title = tabName();
            mArea = options.area;
            mMaxmin = options.maxmin;
            isOpenTab = options.tab;
            myToolbar = options.toolbar;
            //如果不调用默认的方法，只需要重新命名，然后设置回调方法即可
            table.on('tool(' + tabId + ')', function (obj) { // 双击 toolDouble
                let _id = obj.data._id;

                if (obj.event === 'del') {
                    _delete(_id)
                } else if (obj.event === 'disable') {
                    _disable(obj.data._status === 1 ? "禁用" : "启用", _id)
                } else if (obj.event === 'destroy') {
                    _destroy(_id)
                } else if (obj.event === 'edit') {
                    edit(_id)
                } else if (obj.event === 'detail') {
                    detail(_id)
                } else {
                    //触发单元格工具事件
                    if (options.onEvent) {
                        options.onEvent(obj.event, _id, obj);
                    }
                }
            });
            // 渲染
            table.render({
                elem: "#" + tabId,
                toolbar: myToolbar,
                defaultToolbar: options.toolbar ? defaultToolbar : [],
                url: __basePath + pUrl + "/list",
                method: 'post',
                page: pageParams,
                where: whereData,
                height: function () {
                    return $("#" + tabId).parent().outerHeight() - 15; // 返回 number 类型
                }, // 最大高度减去其他容器已占有的高度差
                limit: 15,
                cols: [options.cols],
                done: function (res, curr, count) {
                    if (count === 0) {
                        $(".layui-none").html('<div style="margin-top: 30px;"><img src=' + __basePath + '/assets/images/data-empty.png><br/><span>暂无数据</span></div>');
                    }

                },
                loading: true, // 显示默认加载条
                tree: options.tree

            });
            if (options.rowDouble) {
                // 行双击事件
                table.on('rowDouble(' + tabId + ')', function (obj) {
                    options.rowDouble(obj.data._id, obj);
                });
            }
            if (options.onToolbar) {
                table.on('toolbar(' + tabId + ')', function (obj) {
                    options.onToolbar(obj.event, obj);
                });
            }
            // 渲染
            laydate.render({
                elem: '.table-search-date'
            });

        }, reload: function (field) {
            // 执行搜索重载
            reload(field)
        }, refresh: function () {
            table.reload(tabId, {
                page: pageParams
            });
        }, statuRefresh: function () {
            table.reload(tabId);
        }, checkTableData: function () {
            var checkStatus = table.checkStatus(tabId);
            return checkStatus.data;
        }, checkTableId: function () {
            return tableIds();
        }, openTab: function (a, d) {
            mOpenTab(a, d)
        }, openIframe: function (url, title, area) {
            open(url, title, area);
        }, add: function (area, maxmin) {
            open(pUrl + "/add", "新增", area, maxmin);
        }, expandAll: function (expand) {
            table.expandAll(tabId, expand); // 关闭全部节点
        }, exportFile: function (id) {
            table.exportFile(id, null, "xlsx");
        }, edit: function (id) {
            edit(id)
        }, detail: function (id) {
            detail(id)
        }


    }

    function detail(_id) {
        if (isOpenTab) {
            mOpenTab(pUrl + "/detail?_id=" + _id, activeTabTitle + "-详情")
        } else {
            open(pUrl + "/detail?_id=" + _id, "详情", mArea, mMaxmin);
        }
    }

    function edit(_id) {
        if (_id.startsWith("GENRATOR_")) {
            mOpenTab(pUrl + "/editGenerator?_id=" + _id, activeTabTitle + "-编辑")
        } else {
            if (isOpenTab) {
                mOpenTab(pUrl + "/edit?_id=" + _id, activeTabTitle + "-编辑")
            } else {
                open(pUrl + "/edit?_id=" + _id, "编辑", mArea, mMaxmin);
            }
        }
    }

    /**
     * a
     * @param a 地址
     * @param d 名字
     */
    let mOpenTab = function (a, d) {
        let p = r(parent.document);
        let l, u = p.find("#LAY_app_tabsheader>li")
        u.each(function (e) {
            let i = r(this), n = i.attr("lay-id");
            if (n === a && !l) {
                l = n
            }
        });
        let pid = ""
        if (!l) {
            let app_body = p.find("#LAY_app_body")
            pid = app_body.find(".layui-show>iframe").attr("id")
            app_body.find('.layui-show').removeClass("layui-show");
            app_body.append(['<div class="layadmin-tabsbody-item layui-show">', '<iframe src="' + __basePath + a + '" frameborder="0" class="layadmin-iframe"  scrolling="auto" name="' + d + '" id="' + a + '" pid="' + pid + '" tab="tab"></iframe>', "</div>"].join(""))
            window.parent.layui.element.tabAdd(o, {title: "<span>" + d + "</span>", id: a, attr: pid});
        }
        t.index = u.length;
        top.layui.element.tabChange(o, a);
        //n.tabsBodyChange(t.index, {url: a, text: d, attr: pid})
    }

    function open(url, title, area, maxmin) {
        layer.open({
            type: 2,
            title: activeTabTitle + "-" + title,
            shadeClose: false,
            maxmin: maxmin, //开启最大化最小化按钮
            scrollbar: false,
            area: mArea,
            content: [__basePath + url, 'yes']
        });
    }

    let tableIds = function () {
        const checkStatus = table.checkStatus(tabId);
        const data = checkStatus.data;
        if (data) {
            var ids = [];
            $.each(data, function (k, v) {
                ids.push(v._id)
            });
            return ids.toString();
        }
        return "";
    }
    var reload = function (field) {
        table.reload(tabId, {
            toolbar: myToolbar,
            page: pageParams, where: field // 搜索的字段

        });
    }

    // 将JavaScript对象转换为URL查询参数
    function objectToQueryParams(paramsObj) {
        console.log(paramsObj);
        // 存储键值对的数组
        const queryParts = [];

        // 遍历对象的每个属性
        for (const key in paramsObj) {
            // 检查是否是对象自身的属性，而非原型链上的
            if (paramsObj.hasOwnProperty(key)) {
                const value = paramsObj[key];

                // 对键和值进行URL编码
                const encodedKey = encodeURIComponent(key);
                let encodedValue;

                // 处理不同类型的值
                if (value === null || value === undefined) {
                    encodedValue = '';
                } else if (typeof value === 'object') {
                    // 如果值是对象或数组，转换为JSON字符串
                    encodedValue = encodeURIComponent(JSON.stringify(value));
                } else {
                    encodedValue = encodeURIComponent(String(value));
                }

                // 添加到数组中
                queryParts.push(`${encodedKey}=${encodedValue}`);
            }
        }
        console.log(queryParts);
        // 用&连接所有键值对
        return queryParts.join('&');
    }

    // 搜索提交
    form.on('submit(table-search)', function (data) {
        var field = data.field; // 获得表单字段
        reload(field);
        return false; // 阻止默认 form 跳转
    });
    r('#btn-search-reset').on('click', function () {
        reload({})
    });
    util.on({
        deletes: function () {
            _delete(tableIds())
        }, destroy: function () {
            _destroy(tableIds())
        }, add: function () {
            let url = pUrl + "/add";
            const queryString = objectToQueryParams(whereData);
            if (queryString) {
                url += "?" + queryString
            }
            if (isOpenTab) {
                mOpenTab(url, activeTabTitle + "-新增")
            } else {
                open(url, "新增", mArea, mMaxmin);
            }
        },
        generator: function () {
            mOpenTab(pUrl + "/addGenerator", activeTabTitle + "-模板配置")
        }
    });
    exports("index", tableLoad)
});
